package com.mate.cloud.auth.controller;


import com.mate.cloud.auth.dto.UmsAdminLoginParam;
import com.mate.cloud.auth.dto.UpdateAdminPasswordParam;
import com.mate.cloud.auth.exception.AuthBusinessRuntimeException;
import com.mate.cloud.auth.exception.UserExceptionEnumCode;
import com.mate.cloud.auth.service.UmsAdminService;
import com.mate.cloud.core.common.constant.TokenConstant;
import com.mate.cloud.protocol.response.BaseResponse;
import com.mate.cloud.protocol.web.controller.AdminBaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理后台用户
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createDate: 2023/10/29 18:19
 * @updateUser: MI
 * @updateDate: 2023/10/29 18:19
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
@RestController
@Tag(name = "UserAdminController", description = "后台用户管理")
@RequestMapping("/admin")
public class UserAdminController extends AdminBaseController {

    @Resource
    private UmsAdminService adminService;

    /**
     * 获取当前用户
     *
     * @param umsAdminLoginParam 用户登录参数
     * @return
     */
    @Operation(summary = "登录以后返回token")
    @PostMapping("/login")
    public BaseResponse login(@RequestBody UmsAdminLoginParam umsAdminLoginParam) {

//        throw new AuthBusinessRuntimeException(UserExceptionEnumCode.USER_PWD_ERROR.getCode());
        String token = adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (token == null) {
            throw new AuthBusinessRuntimeException(UserExceptionEnumCode.USER_PWD_ERROR.getCode());
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", TokenConstant.BEARER);
        return successCodeResponse();
    }

    /**
     * 获取当前已经登录用户的信息
     *
     * @return
     */

    @GetMapping("/index")
    public BaseResponse index() {
        Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
        // 得到当前的认证信息
        if (currentAuthentication != null) {
            final String name = currentAuthentication.getName();
            final Collection<? extends GrantedAuthority> authorities = currentAuthentication.getAuthorities();
            log.info("当前登录用户:{}", name);
            log.info("User authorities:{}", authorities);
        }
        return successBodyResponse(currentAuthentication);
    }
    @GetMapping("/hello")
    public BaseResponse hello() {
        return successMsgResponse("/hello");
    }
    /**
     * 获取当前已经登录用户所有权限的集合
     *
     * @return
     */
    @GetMapping("/authority")
    public BaseResponse authority() {
        Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
        // 得到当前的认证信息
        if (currentAuthentication != null) {
            final Collection<? extends GrantedAuthority> authorities = currentAuthentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                log.info("用户权限: {}", authority.getAuthority());
            }
        }
        return successBodyResponse(currentAuthentication.getAuthorities());
    }

    /**
     * 退出方法
     *
     * @return
     */
    @GetMapping("/logout")
    public BaseResponse logout() {
        SecurityContextHolder.clearContext();
        return successCodeResponse();
    }

    /**
     * 刷新token
     *
     * @param request 用户token
     * @return
     */
    @GetMapping("/refreshToken")
    public BaseResponse refreshToken(HttpServletRequest request) {
        String token = getHeaderToken(request);
        // Logic for refreshing the token
        String refreshedToken = adminService.refreshToken(token);
        if (refreshedToken == null) {
            throw new AuthBusinessRuntimeException(UserExceptionEnumCode.TOKEN_REFRESH_ERROR.getCode());
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", TokenConstant.BEARER);
        return successBodyResponse(tokenMap);
    }

    /**
     * 修改指定用户密码
     *
     * @param updatePasswordParam 用户登录参数
     * @return
     */
    @Operation(summary = "修改指定用户密码")
    @PostMapping("/updatePassword")
    public BaseResponse updatePassword(@RequestBody UpdateAdminPasswordParam updatePasswordParam) {
        return successBodyResponse(adminService.updatePassword(updatePasswordParam));
    }
}
